﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Configuration;

namespace WMS.DAL.Factory
{
    internal sealed class DataAccessCache<T>
    {
        private static readonly object lockObj = new object();
        private static readonly string dllPath = ConfigurationManager.AppSettings["SQLiteDAL"];
        private static IDictionary<string, T> objectListCache = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
        private static Assembly dbDllCache = null;
        static DataAccessCache()
        {
            LoadDBDll();
        }

        /// <summary>
        /// 对象缓存到列表中
        /// </summary>
        /// <param name="className"></param>
        /// <returns></returns>
        public static T GetObject(string className, string cacheKeyPre)
        {
            #region
            if (dbDllCache == null)
            {
                LoadDBDll();
            }

            string cacheKey = string.Format("{0}{1}", cacheKeyPre, className);
            if (objectListCache.ContainsKey(cacheKey))
            {
                return objectListCache[cacheKey];
            }

            T t = (T)dbDllCache.CreateInstance(className);

            objectListCache.Add(cacheKey, t);

            return t;
            #endregion
        }

        private static void LoadDBDll()
        {
            if (dbDllCache == null)
            {
                lock (lockObj)
                {
                    if (dbDllCache == null)
                    {
                        dbDllCache = Assembly.Load(dllPath);
                    }
                }
            }
        }
    }
}
